<script>
import SearchControl from '../components/SearchControl.vue'
import ActivityItem from '../components/ActivityItem.vue'
import Page from '../components/Page.vue'

export default {
  name: 'ActivitiesView',
  data() {
    return {
      banner: {},
      page: {},
      activities: []
    }
  },

  computed: {
    adBanner() {
      return {
        'address': this.banner.address,
        'imgSrc': 'http://image.fit-start.co/news_ad.png'
      }
    },

    currentPage() {
      return Number(this.$store.state.route.query.page) || 1
    },

    q() {
      return this.$store.state.route.query.q
    },

    query() {
      return {
        page: this.currentPage,
        q: this.q
      }
    }
  },

  components: {
    Page,
    ActivityItem,
    SearchControl
  },

  watch: {
    currentPage(page) {
      this.loadActivities(page)
    },

    q(value) {
      this.loadActivities(this.currentPage, value)
    }
  },

  methods: {
    loadActivities(page, queryName = this.q) {
      if (queryName) {
        this.$route.query.q = queryName
      }
      this.$store
        .dispatch('FETCH_ACTIVITIES', { params: this.$route.query })
        .then(() => {
          this.activities = this.$store.state.activity.activities
          this.page = this.$store.state.activity.page
        })
    },

    loadPageConfig() {
      this.$store
        .dispatch('FETCH_PAGE_CONFIG', { page: 'activity' })
        .then((data) => {
          this.banner = data.link_activity_list[0]
        })
    },

    changeQueryName(value) {
      let query = this.query
      query.q = value
      let queryString = Object.keys(query)
        .filter(key => !!query[key])
        .map(key => `${key}=${query[key]}`)
        .join('&')
      let url = queryString ? `${this.$route.path}?${queryString}` : this.$route.path
      this.$router.push(url)
    }
  },

  beforeMount() {
    this.loadActivities(this.currentPage)
    this.loadPageConfig()
  }
}
</script>

<template>
<div class="container events clearfix" id="activities-view">

  <a class="ad" :href="adBanner.address">
    <img :src="adBanner.imgSrc" >
    <button class="close-btn hide"></button>
  </a>

  <div class="activities-toolbar">
    <div class="title">
      <h1>活动列表</h1>
    </div>

    <search-control :value="q"
      :placeholder="'活动名称'"
      @searchcontrol-change="changeQueryName">
    </search-control>
  </div>
  
  <ul class="activities-list list clearfix">
    <activity-item v-for="activity in activities" :activity="activity"></activity-item>  
  </ul>
  
  <page :prePage="page.prePage"
    :prePages="page.prePages"
    :currentPage="page.currentPage"
    :nextPage="page.nextPage"
    :nextPages="page.nextPages">
  </page>

</div>
</template>

<style>
@import '../../static/styles/activities.css';
</style>